package com.gears_software.sxdc.dccx.ui.activity;

import android.Manifest;
import android.app.AppOpsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.gears_software.sxdc.dccx.R;
import com.gears_software.sxdc.dccx.application.DCCXApplication;
import com.gears_software.sxdc.dccx.data.adapter.FragmentAdapter;
import com.gears_software.sxdc.dccx.data.finder.IMemberFinder;
import com.gears_software.sxdc.dccx.data.finder.util.GearsErrorHandler;
import com.gears_software.sxdc.dccx.data.model.MsgModel;
import com.gears_software.sxdc.dccx.data.sharedPreference.DCCXSp_;
import com.gears_software.sxdc.dccx.ui.event.LogoutDriverMemberEvent;
import com.gears_software.sxdc.dccx.ui.event.IsAutoLocationEvent;
import com.gears_software.sxdc.dccx.ui.fragment.CarPoolFragment;
import com.gears_software.sxdc.dccx.ui.fragment.CarPoolFragment_;
import com.gears_software.sxdc.dccx.ui.fragment.SpecialCarFragment;
import com.gears_software.sxdc.dccx.ui.fragment.SpecialCarFragment_;
import com.gears_software.sxdc.dccx.ui.util.MyViewPager;
import com.gears_software.sxdc.dccx.ui.util.OttoBus;
import com.gigamole.navigationtabstrip.NavigationTabStrip;
import com.github.mzule.activityrouter.annotation.Router;
import com.github.mzule.activityrouter.router.Routers;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.sdsmdg.tastytoast.TastyToast;
import com.umeng.analytics.MobclickAgent;
import com.yanzhenjie.alertdialog.AlertDialog;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.yanzhenjie.permission.SettingService;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.androidannotations.rest.spring.annotations.RestService;

import java.util.ArrayList;
import java.util.List;

import qiu.niorgai.StatusBarCompat;

@EActivity(R.layout.activity_main)
@Router(value = "main", isEActivity = true)
public class MainActivity extends BaseActivity {

    @App
    DCCXApplication app;
    @Pref
    DCCXSp_ sp;
    @ViewById
    public TextView actionbar_title;
    @ViewById
    public TextView back_icon;
    @ViewById
    public TextView right_icon;
    @ViewById
    NavigationTabStrip navigationTabStrip;
    @ViewById
    MyViewPager viewpager;
    @Bean
    GearsErrorHandler errorHandler;
    @RestService
    IMemberFinder memberFinder;
    @Bean
    OttoBus bus;
    String[] titles = {"拼车", "专车" };
    FragmentAdapter adapter;
    List<Fragment> pages = new ArrayList<Fragment>();
    Context context;
    CarPoolFragment carPool;
    SpecialCarFragment specialCar;
    String isLogout;
    private long exitTime = 0;
    public static MainActivity instance;
    MsgModel msgModel;


    @AfterViews
    void created() {

        context = this;
        instance = this;
        actionbar_title.setText("大昌出行");
        initIconfont();
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorActionbar));
        initViewPager();
        initNavTabStrip();
        //获取定位权限
        AndPermission.with(context)
                .requestCode(200)
                .permission(Permission.LOCATION)
                .callback(listener)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(context, rationale).show();
                    }
                })
                .start();
    }


    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            if (requestCode == 200) {
//                TastyToast.makeText(context, "获取定位权限成功", TastyToast.LENGTH_SHORT, TastyToast.SUCCESS);
                boolean flag = AndPermission.hasPermission(MainActivity.this,Permission.LOCATION);
                if (AndPermission.hasPermission(MainActivity.this,Permission.LOCATION)){
                    //执行相应操作
                }else{
                    AndPermission.defaultSettingDialog(MainActivity.this, 400).show();
                }
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            if (requestCode == 200) {
                TastyToast.makeText(context, "获取定位权限失败", TastyToast.LENGTH_SHORT, TastyToast.ERROR);
                if (AndPermission.hasAlwaysDeniedPermission(MainActivity.this, deniedPermissions)) {
                    AndPermission.defaultSettingDialog(MainActivity.this, 400).show();
//                    getDefaultSetting();
                }
            }
        }
    };

    private void getDefaultSetting() {
        new MaterialDialog.Builder(context)
                .title("提示")
                .titleGravity(GravityEnum.CENTER)
                .titleColorRes(R.color.colorFontGray)
                .content("您拒绝了我们必要的定位权限,请在设置中进行应用定位授权！")
                .contentColorRes(R.color.black)
                .positiveText("授权")
                .positiveColor(ContextCompat.getColor(context, R.color.colorFontBlue))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        startActivityForResult(new Intent(Settings.ACTION_SETTINGS), 400); //直接进入手机中设置界面
                    }
                })
                .negativeText("取消")
                .negativeColor(ContextCompat.getColor(context, R.color.colorFontGray))
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                })
                .buttonsGravity(GravityEnum.CENTER)
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 400: {
                // This is the 400 you are above the number of incoming.
                if (AndPermission.hasPermission(MainActivity.this, Permission.LOCATION)) {
                    TastyToast.makeText(this, "获取定位权限成功", app.SHORT, app.SUCCESS);
                    //执行相应操作

                } else {
                    TastyToast.makeText(this, "获取定位权限失败", app.SHORT, app.ERROR);

                }
                break;
            }
        }

    }

    void initIconfont() {
        back_icon.setTypeface(app.iconfont);
        right_icon.setTypeface(app.iconfont);
    }

    void initViewPager() {
        carPool = new CarPoolFragment_();
        specialCar = new SpecialCarFragment_();
        pages.add(carPool);
        pages.add(specialCar);
        adapter = new FragmentAdapter(getSupportFragmentManager(), pages, titles);
        viewpager.setAdapter(adapter);
        viewpager.setCurrentItem(0);
    }

    void initNavTabStrip() {
        navigationTabStrip.setTitles(titles);
        navigationTabStrip.setTitleSize(getResources().getDimensionPixelSize(R.dimen.normal_font_size));
//        navigationTabStrip.setStripColor(ContextCompat.getColor(this,R.color.colorActionbar));
        navigationTabStrip.setStripWeight(0);
        navigationTabStrip.setStripFactor(2);
        navigationTabStrip.setStripGravity(NavigationTabStrip.StripGravity.BOTTOM);
        navigationTabStrip.setStripType(NavigationTabStrip.StripType.LINE);
        navigationTabStrip.setTypeface("fonts/typeface.ttf");
        navigationTabStrip.setCornersRadius(3);
        navigationTabStrip.setAnimationDuration(300);
        navigationTabStrip.setInactiveColor(ContextCompat.getColor(this, R.color.colorTabFont));
        navigationTabStrip.setActiveColor(ContextCompat.getColor(this, R.color.colorActionbar));
        navigationTabStrip.setViewPager(viewpager, 0);
        app.index = 0;
        navigationTabStrip.setOnTabStripSelectedIndexListener(new NavigationTabStrip.OnTabStripSelectedIndexListener() {
            @Override
            public void onStartTabSelected(String title, int index) {

            }

            @Override
            public void onEndTabSelected(String title, int index) {
                app.index = index;
                if (index == 0) {
                    specialCar.modifyState();
                }
                specialCar.onIsAutoLocation(index);


            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            if (intent.getExtras().get("isLogout") != null) {
                isLogout = (String) intent.getExtras().get("isLogout");
                if (isLogout.equals("1")) {
                    bus.post(new LogoutDriverMemberEvent());
                    TastyToast.makeText(this, "您的账号已在别处登录", app.SHORT, app.WARNING);
                }
            }
        }
    }


    @Click
    void back_icon() {
        if (specialCar.isFirst) {
            Routers.open(this, "gears_dccx://myinfo");
        } else {
            specialCar.modifyState();
        }
    }

    @Click
    void right_icon() {
        Routers.open(this, "gears_dccx://messagecenter");

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (specialCar.isFirst) {
                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    TastyToast.makeText(getApplicationContext(), "再按一次退出程序", app.SHORT, app.WARNING);
                    exitTime = System.currentTimeMillis();
                } else {
                    finish();
                    System.exit(0);
                }
                return true;
            } else {
                specialCar.modifyState();
                return true;
            }
        }

        return super.onKeyDown(keyCode, event);

    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("MainActivity"); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写。"SplashScreen"为页面名称，可自定义)
        MobclickAgent.onResume(this); //统计时长

    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MainActivity");
        MobclickAgent.onPause(this);
    }

}
